import { createRouter, createWebHashHistory } from "vue-router";
import {useUserStore} from "@/stores/index.js";

// ()=>{return xxx}，否则不加
const routes = [
    {
        path: "/",
        name: "welcome",
        component: () => import("@/views/common/Welcome.vue"),
        children: [
            {
                path: "",
                name: "welcome-login",
                component: () => import("@/components/welcome/LoginPage.vue"),
            },
            {
                path: "register",
                name: "welcome-register",
                component: () => import("@/components/welcome/RegisterPage.vue"),
            },
            {
                path: "forget",
                name: "welcome-forget",
                component: () => import("@/components/welcome/ForgetPage.vue"),
            },
        ],
    },
    {
        path: "/index",
        name: "index",
        component: () => import("~@/views/common/Index.vue"),
    },
    {
        path: "/test",
        name: "test",
        component: () => import("~@/views/test.vue"),
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

router.beforeEach((to, from, next)=> {
    const userStore = useUserStore()
    if (userStore.auth.user != null && to.name.startsWith("welcome-")) {
        next('/index')
    } else if (userStore.auth.user == null && to.fullPath.startsWith('/index')) {
        next('/')
    } else if(to.matched.length === 0) {
        next('/index')
    } else {
        next()
    }
})
// 要到导出，别的才能导入
export default router;
